// pages/login/login.js
const app = getApp();
const utils = require('../../utils/util.js');
const call = require('../../utils/request.js');
var interval = null //倒计时函数
Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    phoneNumber: '',
    inputAuthCode: null,
    time: '获取验证码',
    currentTime: 60,
    isClick: true,
    isAgree: false,
    toast: ''
  },
  onLoad: function(options) {
    this.getUser();
  },
  getUser() { //获取用户信息
    let that = this;
    if (app.globalData.userInfo) {
      that.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (that.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        that.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          that.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getAuthCode() { //点击获取验证码
    let that = this;
    var {
      currentTime
    } = that.data;
    //验证手机号码
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/; // 判断手机号码的正则
    if (that.data.phoneNumber.length == 0) {
      wx.showToast({
        title: '手机号码不能为空',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    if (that.data.phoneNumber.length < 11) {
      wx.showToast({
        title: '手机号码长度有误！',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    if (!myreg.test(that.data.phoneNumber)) {
      wx.showToast({
        title: '错误的手机号码！',
        icon: 'none',
        duration: 2000
      })
      return;
    }


    that.setData({ //禁止点击
      isClick: false,
    })
    interval = setInterval(() => { //60s倒计时
      currentTime--;
      that.setData({
        time: '获取验证码（' + currentTime + '）'
      });
      if (currentTime <= 0) {
        clearInterval(interval);
        that.setData({
          time: '获取验证码',
          currentTime: 60,
          isClick: true
        })
      }
    }, 1000);
    //请求验证码接口，并记录服务器返回的验证码用于判断，这里服务器也可能不返回验证码，那验证码的判断交给后台*/
    //获取验证码接口,输入手机号，获取验证码authCode并设置data，接口3
    // wx.request({})
    const url = `/service/app/v1/account/getMobileCode?access_token=defaultAccessToken`;
    const params = {
      "header": {},
      "data": {
        "cellphone": that.data.phoneNumber,
        "type": 1
      }
    };
    console.log('发送信息', url, params)
    call.postData(url, params, res => {
      console.log('获取验证码成功', res);
    }, err => {
      console.log('获取验证码失败', err)
    })
  },
  subPhoneNumber(e) { //获取用户输入的手机号
    this.setData({
      phoneNumber: e.detail.value
    })
  },
  subAuthCode(e) { //获取用户输入的验证码
    this.setData({
      inputAuthCode: e.detail.value
    });
  },

  loginIn() { //点击登录验证用户信息
    // 必须是在用户已经授权的情况下调用
    let that = this;
    const {
      isAgree,
      phoneNumber,
      inputAuthCode
    } = that.data;
    if (isAgree && inputAuthCode && phoneNumber.length !== 0) {
      const url = `/service/app/v1/account/userRegisterOrBind?access_token=${app.globalData.access_token}`;
      const params = {
        "header": {},
        "data": {
          "cellphone": phoneNumber,
          "userAccount": "",
          "securityCode": inputAuthCode,
          "openId": app.globalData.openId,
          "headImgUrl": "",
          "nickName": ""
        }
      }
      console.log('上传的信息', params);
      call.postData(url, params, res => {
        console.log('验证用户信息成功', res);
        if (res.state === "000000") {
          console.log('验证成功');
          app.globalData.userId = res.data.userId;
          wx.setStorage({
            key: 'userId',
            data: res.data.userId,
          })
          wx.removeStorage({
            key: 'log',
            success(res) {
              app.globalData.phoneNumber = that.data.phoneNumber
              wx.reLaunch({
                url: '../foodmanager/foodmanager'
              })
            },
            fail() {
              wx.showToast({
                title: '无法移除该缓存',
                icon: 'none'
              })
            }
          })
        } else {
          console.log('验证码有误', res);
          wx.showToast({
            title: res.data,
            icon: 'none'
          })
        }
      }, err => {
        console.log('验证用户信息失败', err)
      })

    } else {
      var title = '';
      if (!isAgree) {
        title = '请阅读并同意条款'
      } else if (!inputAuthCode) {
        title = '验证码不能为空'
      } else {
        title = '请填写完整的手机号'
      }
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 3000
      })
    }

  },
  agree() {
    this.setData({
      isAgree: !this.data.isAgree
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})